<template>
    <view class="box">
        <!-- 引入 nav-bar 组件，并传递页面标题 -->
        <nav-bar :navTitle="navTitle" />
        <view class="top">
            <view 
                class="autoPay autoPayLeft" 
                :class="{ active: selectedPayType ==='self' }"
                @click="selectPayType('self')"
            >
                自 助 交 费
            </view>
            <view 
                class="autoPay autoPayRight" 
                :class="{ active: selectedPayType === 'bill' }"
                @click="selectPayType('bill')"
            >
                账 单 交 费
            </view>
        </view>
        <view v-if="selectedPayType ==='self'" class="content">
            <view class="input-row">
				<view class="label">自定金额</view>
				
				<input
					:class="{ 'input-error': isAmountInvalid }"
					placeholder="请输入充值金额" 
					@input="handleAmountInput" 
					type="digit" 
						placeholder-style="color:rgba(254, 114, 92, 0.67)" 
				/>
				
				<!-- <input 
				      v-model="amount" 
				      type="digit" 
				      placeholder="请输入金额"
				      @input="handleInput"
				    /> -->
					<!--  -->
					<!-- <input 
						v-model="amount"
						:class="{ 'input-error': isAmountInvalid }"
						placeholder="请输入充值金额" 
						@input="handleAmountInput" 
						type="digit" 
						placeholder-style="color:rgba(254, 114, 92, 0.67)" 
					/> -->
					
					
					
				</view>
				<view v-if="isAmountInvalid" class="error-tip">充值金额必须大于零且最多两位小数</view>
				
				<view class="input-row">
					<view class="label">备注信息</view>
					<input 
						:class="{ 'input-error': isRemarkInvalid }"
						placeholder="仅限文字、数字;20字以内" 
						type="text" 
						placeholder-style="color:rgba(254, 114, 92, 0.67)" 
						@input="handleRemarkInput" 
					/>
				</view>
            <view v-if="isRemarkInvalid" class="error-tip">备注信息，仅限文字、数字；20字以内</view>
            <view class="img" @click="goFapiaoOrder">
                <image src="/static/images/kjfp.png" mode="" />
                订单&发票
            </view>
            <button @tap="jiaofei">确认支付</button>
        </view>
    </view>
</template>

<script>
const app = getApp();
const $http = app.globalData.$http;
var config = require('../../utils/config.js');
export default {
    data() {
        return {
            picUrl: config.Config,
            amount: '',
            merchantCode: '',
            selectedPayType:'self',
            remark: '',
            isRemarkInvalid: false,
			isAmountInvalid: false,
            publicService: '',
            // 设置页面标题
            navTitle: '水费',
			// 输入是否符合要求
			isValid:false,
			
        };
    },
    onLoad(options) {
        this.setData({
            merchantCode: options.merchantCode
        });
    },
    methods: {
		 
        selectPayType(type) {
            this.selectedPayType = type;
        },
        goFapiaoOrder: function () {
            if (uni.getStorageSync('token') == '') {
                uni.showToast({
                    title: '您还未登录，请先登录',
                    icon: 'none'
                });
                setTimeout(function () {
                    uni.navigateTo({
                        url: '/pages/login/index'
                    });
                }, 1200);
            } else {
                uni.navigateTo({
                    url: '/pages/fapiaoAndOrder/index'
                });
            }
        },
		
		handleInput(event) {
		   const inputValue = event.detail.value;
			 
		   // 正则表达式：允许数字和最多一个小数点
		   let result = inputValue.replace(/[^0-9.]/g, ""); // 清除非数字和小数点字符
		   result = result.replace(/^\.+|[^\d]\.|(?<=\.)\./g, ""); // 移除多余的小数点
		   // result = result.replace(/\.{2,}/g, "."); // 处理连续小数点的情况
			const firstDotIndex = result.indexOf('.');
		   if (firstDotIndex!== -1) {
			   result = result.slice(0, firstDotIndex + 1) + result.slice(firstDotIndex + 1).replace(/\./g, '');
		   }
					   	 
		   this.$nextTick(() => {
			 this.amount = result;
		   });
		},
		
		handleAmountInput(e) {
			let value = e.detail.value;
			const originalValue = value;
		
			// 过滤非数字和非小数点字符
			value = value.replace(/[^\d.]/g, '');
		
			// 处理多个小数点
			const dotCount = (value.match(/\./g) || []).length;
			if (dotCount > 1) {
				value = value.slice(0, value.lastIndexOf('.'));
			}
		
			// 处理以小数点开头的情况
			if (value.startsWith('.')) {
				value = '0' + value;
			}
		
			// 验证金额是否大于零且小数位数不超过两位
			this.isValid = value!== '' && parseFloat(value) > 0;
			
			if (value.includes('.')) {
				const decimalPart = value.split('.')[1];
				this.isValid = this.isValid && decimalPart.length <= 2;
			}
			
			this.isAmountInvalid =!this.isValid;
			console.log('打印：',this.isAmountInvalid);
		
			if (originalValue!== value ||!this.isValid) {
				this.amount = '';
				
			} else {
				this.amount = value;
			}
		},
		
		// handleAmountInput(e) {			
							
		// 	const inputValue = e.detail.value;
										 
		//    // 正则表达式：允许数字和最多一个小数点
		//    let result = inputValue.replace(/[^0-9.]/g, ""); // 清除非数字和小数点字符
		//    result = result.replace(/^\.+|[^\d]\.|(?<=\.)\./g, ""); // 移除多余的小数点
		// 	// 处理以小数点开头的情况
		// 	if (inputValue.startsWith('.')) {
		// 		result = '0' + inputValue;
		// 	}
		// 	// 控制小数点后最多两位
		// 	const decimalIndex = inputValue.indexOf('.');
		// 	if (decimalIndex >= 0 && inputValue.length - decimalIndex > 3) { 
		// 		result = inputValue.substring(0, decimalIndex + 3); 
		// 	}
		// 		console.log('result:',result);		 
		//    this.$nextTick(() => {
		// 	 this.amount = result;
		//    });
				
				
				
		// },
		
		
        handleRemarkInput(e) {
            const value = e.detail.value;
            const isValid = /^[a-zA-Z0-9\u4e00-\u9fff]{0,20}$/.test(value);
            this.setData({
                remark: value,
                isRemarkInvalid:!isValid
            });
        },
        jiaofei() {
			
			if (this.isRemarkInvalid || this.isAmountInvalid) {
				uni.showToast({
					title: '请按照要求输入，否则不能充值',
					icon: 'none'
				});
				return;
			}
			if (this.amount =='') {
				uni.showToast({
					title: '请输入有效的数字金额，最多两位小数',
					icon: 'none'
				});
				return;
			}

            // 水费，电费，暂停状态下，提示：物业服务已暂停，请联系商管！燃气不做判断。
            // 判断是否暂停
            this.publicService = uni.getStorageSync('publicService');

            if (this.publicService === '1') {
                uni.showToast({
                    title: '物业服务已暂停，请联系商管！',
                    icon: 'none'
                });
                return;
            } else {
				console.log('金额：',this.amount);
                $http
                   .payment({
                        "channel": "WXPAY",
                        "merchantCode": "EW_N9479011740",
                        "openId": uni.getStorageSync('openId'),
                        "orderSource": "1",
                        "orderType": "01",
                        "subAppId": "wx86595b5f9ea5240c",
                        "totalAmount": parseFloat(this.amount),
                        "tradeType": "WX_LITE",
                        "remark": this.remark,
						"body": "水费",
						"subject":"水费"
                    })
                   .then((res) => {
                        console.log('打印返回的res信息：', res);
                        if (res.code === 200) {
                            const payData = JSON.parse(res.data.payData);
                            const packageValue = payData['package'];
                            console.log('packageValue：', packageValue);
                            wx.requestPayment({
                                timeStamp: payData.timeStamp,
                                nonceStr: payData.nonceStr,
                                'package': packageValue,
                                signType: payData.signType,
                                paySign: payData.paySign,
                                success(res) {
                                    console.log('支付成功', res);
                                    // 跳转到订单发票页面
									uni.navigateTo({
										url: '/pages/fapiaoAndOrder/index'
									});
                                   
                                },
                                fail(res) {
                                    console.log('支付失败', res);
                                }
                            });
                        } else {
                            uni.showToast({
                                title: res.msg,
                                icon: 'error'
                            });
                        }
                    });
            }
        }
    }
};
</script>

<style>
    /* 引入HarmonyOS Sans字体 */
/*    @font-face {
        font-family: 'HarmonyOS Sans';
        src: url('/static/fonts/HarmonyOS_Sans_Bold.ttf') format('truetype'); 
        font-weight: 500;
        font-style: normal;
    } */

.box {
        width: 700rpx;
        margin: 0 auto;
        padding-top: 200rpx; /* 进一步增大顶部内边距，给.top 留出更多空间 */
    }

.top {
        height: 80rpx;
        width: 90%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        position: fixed;
        top: 160rpx; /* 往下调整，避免被小程序右上角按钮遮挡 */
        background-color: white;
        z-index: 1;
    }

.autoPay {
        border: 1px solid #EB5A19;
        width: 48%;
        height: 70rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        font-size: 30rpx;
        color: #EB5A19;
    }

.autoPayLeft {
        border-top-left-radius: 10px;
        border-bottom-left-radius: 10px;
    }

.autoPayRight {
        border-top-right-radius: 10px;
        border-bottom-right-radius: 10px;
    }

.autoPay.active {
        background-color: #EB5A19;
        color: white;
    }

.content {
        /* padding: 20rpx; */
		margin-top: 100rpx;
    }

.input-row {
        display: flex;
        align-items: center;
        margin-top: 20rpx;
    }

.label {
        margin-right: 10rpx;
        width: 30%;
        font-weight: bold;
        /* font-family: 'HarmonyOS Sans'; */
        font-weight: 500;
        line-height: 19px;
        letter-spacing: 0px;
        text-align: left;
    }

.box input {
        border: 2rpx solid #ff6e00;
        height: 80rpx;
        width: 100%;
        border-radius: 16rpx;
        padding: 0 10rpx;
        font-size: 32rpx;
        box-sizing: border-box;
    }

.input-error {
        border-color: red;
        border-width: 5rpx !important;
    }

.error-tip {
        color: red;
        font-size: 25rpx;
        margin-top: 5rpx;
        text-align: left;
        padding-left: 25%;
        /* font-family: 'HarmonyOS Sans'; */
        font-weight: 500;
        line-height: 38rpx;
        letter-spacing: 0px;
        text-align: left;
    }

.box button {
        height: 90rpx;
        line-height: 90rpx;
        background-color: #fe725c;
        color: #fff;
        font-size: 32rpx;
        width: 100%;
        box-sizing: border-box;
        margin-top: 10%;
    }

.box.remark {
        margin-top: 5%;
    }

.img {
        display: flex;
        align-items: center;
        justify-content: center;
        color: #231815;
        width: 100%;
        margin-top: 60%;
    }

.img image {
        width: 49rpx;
        height: 46rpx;
        margin-right: 10rpx;
    }

.remark {
        font-size: 24rpx;
        margin-top: 20rpx;
        font-weight: 300;
    }

.no-border-input {
        border: 0 !important;
        -webkit-appearance: none; /* 移除默认样式 */
    }
</style>